package org.jeecg.talentCooperation.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.talentCooperation.util.cache.ISynonymsService;
import org.jeecg.talentCooperation.util.keywords.TfIdfAnalyzer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ChatGptUtil {

//    private String url = "http://127.0.0.1:8000";
    private String url = "http://10.10.10.10:8188";
    private String synonymsUrl = "http://20.164.1.239:8018/words/synonyms";
//    private String synonymsUrl = "http://10.10.10.216:8018/words/synonyms";
//    private String prefix = "Please extract three keywords from the given sentence that accurately represent the main points of the sentence. Each keyword should be sourced from the current sentence and should not exceed 6 characters XXX";
    private String prefix = "抽取下面一句话中最核心的2个词:  XXX";


    @Autowired
    private TfIdfAnalyzer tfIdfAnalyzer;

    @Autowired
    private ISynonymsService synonymsService;

    /**
     * 获取关键词
     * @param contentStr
     * @return
     */
    public List<String> getKeyWordsByGpt(String contentStr){
        List<String> result = new ArrayList<>();
        //添加head
        Map<String, String> head = new HashMap<>();
        head.put("Content-Type", "application/json");
        //拼接内容
        Map<String, String> params = new HashMap<>();
        String content = prefix.replace("XXX", CommonUtil.replaceBlankOfName(contentStr)).replace("“", "").replace("\"", "");
//        System.out.println("----开始生成----关键词,请求体为----" + content);

        params.put("prompt", content);

        String[] resultArr = new String[0];
        try {
            //不生成一直循环
//            while(resultArr.length == 0){
                //根据gpt生成关键词
                String responseBody = ThirdHttpUtil.postJson(url , params, head);

                JSONObject obj = JSON.parseObject(responseBody);
                String responseMsg = obj.getString("response");
                responseMsg = responseMsg.replace("1.", "").replace("2.", "").replace("3.", "").replace("\"", "");
                System.out.println("已生成的成果关键词描述---"+ responseMsg);
                if(responseMsg.contains("，")){
                    resultArr = responseMsg.split("，");
                }else if(responseMsg.contains(",")){
                    resultArr = responseMsg.split(",");
                }else if(responseMsg.contains("、")){
                    resultArr = responseMsg.split("、");
                }else if(responseMsg.contains("\n")){
                    resultArr = responseMsg.split("\n");
                }
                //保留3-6个字的词语
                result = Arrays.stream(resultArr).filter(c -> c.length()>=2 && c.length()<=6).collect(Collectors.toList());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取关键词
     * @param contentStr
     * @return
     */
    public List<String> getKeyWordsByJieba(String contentStr){
        List<String> list = new ArrayList<>();
        try {
            //分析词云 提取
            list = tfIdfAnalyzer.keywords(contentStr);
            System.out.println("分析出的词---"+ list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取近义词
     * @param contentStr
     * @return
     */
//    @Cacheable(cacheNames = "synonymsWord", key = "'synonyms_' + #p0")
    public List<String> getSynonyms(String contentStr){
        List<String> result = new ArrayList<>();
        //拼接内容
        Map<String, String> params = new HashMap<>();

        params.put("question", CommonUtil.replaceBlankOfName(contentStr));

        try {
            String responseBody = ThirdHttpUtil.get(synonymsUrl , params, null);

            System.out.println("已生成的成果近义词描述---"+ responseBody);

            result = JSON.parseArray(responseBody, String.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取关键词及语义近义词
     * @param contentStr
     * @return
     */
    public List<String> getKeyWordsAndSynonymsWord(String contentStr){
        List<String> resultList = new ArrayList<>();

        List<String> gptList = this.getKeyWordsByJieba(contentStr);
        if(!CollectionUtils.isEmpty(gptList)){
            for (String word : gptList) {
                try {
                    List<String> synonymsResultList = synonymsService.getSynonymsFormCache(word, synonymsUrl);
                    if(!CollectionUtils.isEmpty(synonymsResultList)) {
                        resultList.addAll(synonymsResultList);
                    }else{
                        resultList.add(word);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }else{
            List<String> synonymsResultList = synonymsService.getSynonymsFormCache(contentStr, synonymsUrl);
            if(!CollectionUtils.isEmpty(synonymsResultList)) {
                resultList.addAll(synonymsResultList);
            }else{
                resultList.add(contentStr);
            }
        }
        return resultList;
    }

}
